<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库编号" prop="warehousing">
        <el-input
          v-model="queryParams.warehousing"
          placeholder="请输入入库编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="快递单号" prop="stockTrackingnumber">
        <el-input
          v-model="queryParams.stockTrackingnumber"
          placeholder="请输入快递单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="commName">
        <el-input
          v-model="queryParams.commName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库状态" prop="storeStatus">
        <el-select v-model="queryParams.storeStatus" placeholder="请选择入库状态" clearable>
          <el-option
            v-for="dict in dict.type.store_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入库时间" prop="storeTime">
        <el-date-picker clearable
          v-model="queryParams.storeTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择入库时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="包裹状态" prop="packageStatus">
        <el-select v-model="queryParams.packageStatus" placeholder="请选择包裹状态" clearable>
          <el-option
            v-for="dict in dict.type.package_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作员" prop="loginAccount">
        <el-input
          v-model="queryParams.loginAccount"
          placeholder="请输入操作员"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单时间" prop="orderCreateTime">
        <el-date-picker clearable
          v-model="queryParams.orderCreateTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择下单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="客户编号" prop="userAccount">
        <el-input
          v-model="queryParams.userAccount"
          placeholder="请输入客户编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓位类型" prop="positionType">
        <el-select v-model="queryParams.positionType" placeholder="请选择仓位类型" clearable>
          <el-option
            v-for="dict in dict.type.position_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="仓位编号" prop="positionNumber">
        <el-input
          v-model="queryParams.positionNumber"
          placeholder="请输入仓位编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['system:store:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="single"
          @click="wareHousingPackage"
          v-hasPermi="['system:store:edit']"
        >包裹入库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:store:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:store:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="入库编号" align="center" prop="warehousing" />
      <el-table-column label="订单编号" align="center" prop="orderNumber" />
      <el-table-column label="快递单号" align="center" prop="stockTrackingnumber" />
      <el-table-column label="商品名称" align="center" prop="commName" />
      <el-table-column label="入库状态" align="center" prop="storeStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.store_status" :value="scope.row.storeStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="入库时间" align="center" prop="storeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.storeTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="包裹状态" align="center" prop="packageStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.package_status" :value="scope.row.packageStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作员" align="center" prop="loginAccount" />
      <el-table-column label="下单时间" align="center" prop="orderCreateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderCreateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户编号" align="center" prop="userAccount" />
      <el-table-column label="客户名称" align="center" prop="userName" />
      <el-table-column label="仓位类型" align="center" prop="positionType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.position_type" :value="scope.row.positionType"/>
        </template>
      </el-table-column>
      <el-table-column label="仓位编号" align="center" prop="positionNumber" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="wareHousingPackage(scope.row)"
            v-hasPermi="['system:store:edit']"
          >入库</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:store:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--  包裹入库  -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="入库编号" prop="warehousing">
          <el-input v-model="form.warehousing" placeholder="请输入入库编号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入订单编号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="快递单号" prop="stockTrackingnumber">
          <el-input v-model="form.stockTrackingnumber" placeholder="请输入快递单号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="商品名称" prop="commName">
          <el-input v-model="form.commName" placeholder="请输入商品名称" :disabled="true"/>
        </el-form-item>
        <el-form-item label="入库状态" prop="storeStatus">
          <el-select v-model="form.storeStatus" placeholder="请选择入库状态" :disabled="true">
            <el-option
              v-for="dict in dict.type.store_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入库时间" prop="storeTime">
          <el-date-picker clearable
                          v-model="form.storeTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择入库时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="包裹状态" prop="packageStatus">
          <el-select v-model="form.packageStatus" placeholder="请选择包裹状态" :disabled="true">
            <el-option
              v-for="dict in dict.type.package_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作员" prop="loginAccount">
          <el-input v-model="form.loginAccount" placeholder="请输入操作员" />
        </el-form-item>
        <el-form-item label="下单时间" prop="orderCreateTime">
          <el-date-picker clearable
                          v-model="form.orderCreateTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择下单时间"
                          :disabled="true">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户编号" prop="userAccount">
          <el-input v-model="form.userAccount" placeholder="请输入客户编号" :disabled="true"/>
        </el-form-item>
        <el-form-item label="客户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入客户名称" :disabled="true"/>
        </el-form-item>
        <el-form-item label="仓位类型" prop="positionType">
          <el-select v-model="form.positionType" placeholder="请选择仓位类型" :disabled = "true">
            <el-option
              v-for="dict in dict.type.position_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓位编号" prop="positionNumber">
<!--          <el-input v-model="form.positionNumber" placeholder="请输入仓位编号" />-->

          <el-select v-model="form.positionNumber" filterable placeholder="请选择" @change="handleClientChange">
            <el-option v-for="item in positionselectoption" :key="item.id" :label="item.positionNumber" :value="item.positionNumber" >
            </el-option>
          </el-select>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitWareHousing">入 库</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改入库管理对话框 -->
<!--    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>-->
<!--      <el-form ref="form" :model="form" :rules="rules" label-width="80px">-->
<!--        <el-form-item label="入库编号" prop="warehousing">-->
<!--          <el-input v-model="form.warehousing" placeholder="请输入入库编号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="订单编号" prop="orderNumber">-->
<!--          <el-input v-model="form.orderNumber" placeholder="请输入订单编号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="快递单号" prop="stockTrackingnumber">-->
<!--          <el-input v-model="form.stockTrackingnumber" placeholder="请输入快递单号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="商品名称" prop="commName">-->
<!--          <el-input v-model="form.commName" placeholder="请输入商品名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="入库状态" prop="storeStatus">-->
<!--          <el-select v-model="form.storeStatus" placeholder="请选择入库状态">-->
<!--            <el-option-->
<!--              v-for="dict in dict.type.store_status"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--:value="parseInt(dict.value)"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="入库时间" prop="storeTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.storeTime"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择入库时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="包裹状态" prop="packageStatus">-->
<!--          <el-select v-model="form.packageStatus" placeholder="请选择包裹状态">-->
<!--            <el-option-->
<!--              v-for="dict in dict.type.package_status"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--:value="parseInt(dict.value)"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="操作员" prop="loginAccount">-->
<!--          <el-input v-model="form.loginAccount" placeholder="请输入操作员" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="下单时间" prop="orderCreateTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.orderCreateTime"-->
<!--            type="date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            placeholder="请选择下单时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="客户编号" prop="userAccount">-->
<!--          <el-input v-model="form.userAccount" placeholder="请输入客户编号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="客户名称" prop="userName">-->
<!--          <el-input v-model="form.userName" placeholder="请输入客户名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="仓位类型" prop="positionType">-->
<!--          <el-select v-model="form.positionType" placeholder="请选择仓位类型">-->
<!--            <el-option-->
<!--              v-for="dict in dict.type.position_type"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--:value="parseInt(dict.value)"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="仓位编号" prop="positionNumber">-->
<!--          <el-input v-model="form.positionNumber" placeholder="请输入仓位编号" />-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
<!--        <el-button @click="cancel">取 消</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
import { listStore, getStore, delStore, addStore, updateStore } from "@/api/system/store";
import {listDetails} from "@/api/system/details";
import {listShelf} from "@/api/system/shelf";
import {listPosition} from "@/api/system/position";
import {listInfo, updateInfo} from "@/api/system/info";
import {addOutbound, updateOutbound} from "@/api/system/outbound";
import item from "@/layout/components/Sidebar/Item";
import {addOrderlog, listOrderlog} from "@/api/system/orderlog";

export default {
  name: "Store",
  dicts: ['package_status', 'store_status', 'position_type'],
  data() {
    return {
      //订单列表
      logList: [],

      //与当前订单类型匹配的仓位列表
      suitableSelectoption: [],

      //订单列表
      orderTypeselectoption: [],

      //仓位列表
      positionselectoption: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库管理表格数据
      storeList: [],
      // 所有入库表的数据
      allStoreList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      //查询参数
      queryParamsDetail: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        commName: null,
        commSku: null,
        commSpec: null,
        needNumber: null,
        stockTrackingnumber: null
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehousing: null,
        orderNumber: null,
        stockTrackingnumber: null,
        commName: null,
        storeStatus: null,
        storeTime: null,
        packageStatus: null,
        loginAccount: null,
        orderCreateTime: null,
        userAccount: null,
        userName: null,
        positionType: null,
        positionNumber: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehousing: [
          { required: true, message: "入库编号不能为空", trigger: "blur" }
        ],
        orderNumber: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
        stockTrackingnumber: [
          { required: true, message: "快递单号不能为空", trigger: "blur" }
        ],
        commName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        storeStatus: [
          { required: true, message: "入库状态不能为空", trigger: "change" }
        ],
        // storeTime: [
        //   { required: true, message: "入库时间不能为空", trigger: "blur" }
        // ],
        packageStatus: [
          { required: true, message: "包裹状态不能为空", trigger: "change" }
        ],
        loginAccount: [
          { required: true, message: "操作员不能为空", trigger: "blur" }
        ],
        // orderCreateTime: [
        //   { required: true, message: "下单时间不能为空", trigger: "blur" }
        // ],
        // userAccount: [
        //   { required: true, message: "客户编号不能为空", trigger: "blur" }
        // ],
        // userName: [
        //   { required: true, message: "客户名称不能为空", trigger: "blur" }
        // ],
        // positionType: [
        //   { required: true, message: "仓位类型不能为空", trigger: "change" }
        // ],
        // positionNumber: [
        //   { required: true, message: "仓位编号不能为空", trigger: "blur" }
        // ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {

    handleClientChange(selectedpositionNumber) {
      // 在选项数组中查找匹配的仓位
      const selectedPosition = this.positionselectoption.find(
        item => item.positionNumber === selectedpositionNumber
      );

      // 如果找到匹配项则设置客户名称
      if (selectedPosition) {
        this.form.positionNumber = selectedPosition.positionNumber;

        if (selectedPosition.positionType === 0) {
          this.form.positionType = 0;
        }
        else if (selectedPosition.positionType === 1){
          this.form.positionType = 1;
        }
        else if (selectedPosition.positionType === 2){
          this.form.positionType = 2;
        }
      } else {
        this.form.positionNumber = ""; // 没有匹配项时清空
      }
    },

    /** 查询入库管理列表 */
    getList() {
      this.loading = true;
      //方式1：
      listStore(this.queryParams).then(response => {
        this.storeList = response.rows;//分页拿数据，而不是全部拿取
        // this.allStoreList = response.rows;

        this.total = response.total;
        this.loading = false;
      });

      //方式2：不分页查询获取
      listStore().then(response => {
        this.allStoreList = response.rows; //分页拿数据，而不是全部拿取
        console.log("🚀 ~ file: index.vue:240 ~ listProinfo ~ this.productinfoselectoption:", this.allStoreList)
      });

      //仓位列表
      listPosition().then((res) => {
        this.positionselectoption = res.rows
        this.suitableSelectoption = res.rows
        console.log("🚀 ~ file: index.vue:240 ~ listProinfo ~ this.productinfoselectoption:", this.positionselectoption)
      });

      listInfo().then((res) => {
        this.orderTypeselectoption = res.rows
        console.log("🚀 ~ file: index.vue:240 ~ listProinfo ~ this.productinfoselectoption:", this.orderTypeselectoption)
      });

      listOrderlog().then((res) => {
        this.logList = res.rows

      });

      // this.loading = false;

      // listDetails(this.queryParamsDetail).then(response => {
      //   // 将 response.rows 转换为符合表格结构的对象数组
      //   this.storeList = response.rows.map(item => ({
      //     warehousing: "wh" + Date.now() + item.id,  // 入库编号（示例生成规则）
      //     orderNumber: item.orderNumber,       // 订单编号
      //     stockTrackingnumber: item.stockTrackingnumber,  // 快递单号
      //     commName: item.commName,             // 商品名称
      //     storeStatus: 2,                      // 入库状态（固定值）
      //     storeTime: null,                     // 入库时间
      //     packageStatus: 0,                    // 包裹状态（固定值）
      //     loginAccount: "admin",               // 操作员
      //     orderCreateTime: null,               // 下单时间
      //     userAccount: null,                   // 客户编号
      //     userName: null,                      // 客户名称
      //     positionType: null,                  // 仓位类型
      //     positionNumber: null                 // 仓位编号
      //   }));
      //   this.total = response.total;
      //   this.loading = false;
      // });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        warehousing: null,
        orderNumber: null,
        stockTrackingnumber: null,
        commName: null,
        storeStatus: null,
        storeTime: null,
        packageStatus: null,
        loginAccount: null,
        orderCreateTime: null,
        userAccount: null,
        userName: null,
        positionType: null,
        positionNumber: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加入库管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStore(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改入库管理";
      });
    },

    /** 入库按钮操作 */
    wareHousingPackage(row) {




      // 1. 检查当前行入库状态
      if (row.packageStatus === 1) { //  1 表示包裹已入库
        this.$modal.msgWarning("该包裹已入库，不可重复操作");
        return;
      }

      // 2. 未入库则执行原逻辑
      this.reset();
      const id = row.id || this.ids;
      getStore(id).then(response => {
        this.form = response.data;
        if (this.form.packageStatus === 1) {
          this.$modal.msgWarning("该包裹已入库，不可重复操作");
          return;
        }
        this.open = true;
        this.title = "入库操作";

        const selectedOrderType = this.orderTypeselectoption.find(
          item => item.orderNumber === this.form.orderNumber
        );
        // console.log("!!!!!!!!!!!!!!!" + selectedOrderType.orderType)

        // this.positionselectoption.forEach((item, index) => {
        //   if(item.positionType !== selectedOrderType.orderType){
        //
        //   }
        // });

        this.positionselectoption = this.suitableSelectoption;
        // 正确的筛选逻辑
        this.positionselectoption = this.positionselectoption.filter(item => {
          return item.positionType === selectedOrderType.orderType;
        });


      });
    },

    updateInfoStatus(orderDao,storeTime) {//item.orderNumber,item.userName,item.commName,item.stockTrackingnumber
      const selectedOrder = this.orderTypeselectoption.find(
        item => item.orderNumber === orderDao.orderNumber
      );

      if(orderDao.storeStatus === 0){
        selectedOrder.storeStatus = 0;
      }else if(orderDao.storeStatus === 1){
        selectedOrder.storeStatus = 1;
      }else {
        selectedOrder.storeStatus = 0;
      }
      selectedOrder.storeTime = storeTime;
      updateInfo(selectedOrder);

    },

    /** 提交入库按钮 */
    submitWareHousing(){
      // function updateInfoStatus(orderDao) {
      //   const selectedOrder = this.orderTypeselectoption.find(
      //     item => item.orderNumber === orderDao.orderNumber
      //   );
      //
      //   if(orderDao.storeStatus === 0){
      //     selectedOrder.storeStatus = 0;
      //   }else if(orderDao.storeStatus === 1){
      //     selectedOrder.storeStatus = 1;
      //   }
      //
      //   updateInfo(selectedOrder);
      // }

      this.$refs["form"].validate(valid => {
        if (valid) {//单件不需要进来这里
          if (this.form.storeTime != null && this.form.positionNumber != null) {
            this.form.packageStatus = 1;//包裹状态为已入仓
            //this.form.storeStatus = 1;//0或1 入库状态
            //this.form.orderNumber//订单编号

            let sum = 0;
            let whNum = 0;

            this.allStoreList.forEach((item, index) => {
              console.log(`第${index}个元素:`, item);
              // 示例：检查订单入库状态
              if (item.orderNumber === this.form.orderNumber) {//订单编号相同，统计包裹数量
                //全部入库进不来(因为所有包裹都入仓了，会触发msgWarning)

                sum = sum +1;

                if (item.storeStatus === 2){//未入库
                  //统计订单编号相同，部分入库的包裹数量
                  if (item.stockTrackingnumber !== this.form.stockTrackingnumber){
                    const Dataform = {
                      id: item.id,
                      warehousing: item.warehousing,
                      orderNumber: item.orderNumber,
                      stockTrackingnumber: item.stockTrackingnumber,
                      commName: item.commName,
                      storeStatus: 1,
                      storeTime: item.storeTime,
                      packageStatus: item.packageStatus,
                      loginAccount: item.loginAccount,
                      orderCreateTime: item.orderCreateTime,
                      userAccount: item.userAccount,
                      userName: item.userName,
                      positionType: item.positionType,
                      positionNumber: item.positionNumber
                    };
                    updateStore(Dataform);
                    this.updateInfoStatus(Dataform,item.storeTime);
                    // this.$modal.msgError("LOG1");

                  }
                  else {//入自己
                    if(this.form.positionType === 0){//单件特殊处理
                      this.form.storeStatus = 0;


                      updateStore(this.form).then(response => {


                        // this.$modal.msgSuccess("入自己包裹入库成功");

                        //更新出库表
                        const outBoundForm = {
                          // id: item.id,
                          outboundId: "Out" + this.form.warehousing,
                          warehousing: this.form.warehousing,
                          orderNumber: this.form.orderNumber,
                          userName: this.form.userName,
                          outboundStatus: 1,
                          loginAccount: null
                        };

                        // 或使用 .then() 处理完成逻辑
                        addOutbound(outBoundForm).then(() => {
                          console.log("出库记录添加成功");


                          let isActive = true; // 初始值为 false，后续可以修改


                          this.logList.forEach((item, index) => {
                            if(item.stockTrackingnumber === this.form.stockTrackingnumber){
                              isActive = false;
                            }
                          });
                          //log
                          if(isActive){
                            const logForm = {
                              id: null,
                              orderNumber: this.form.orderNumber,
                              operateType: 11,
                              operateTime: null,
                              userAccount: this.$store.state.user.name,
                              userName: this.form.userName,
                              commName: this.form.commName,
                              stockTrackingnumber: this.form.stockTrackingnumber
                            };

                            // 生成符合数据库 datetime 格式的时间字符串（本地时区，格式如 "2024-03-29 15:30:45"）
                            const now = new Date();
                            const year = now.getFullYear();
                            const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零（3 → "03"）
                            const day = String(now.getDate()).padStart(2, '0');
                            const hours = String(now.getHours()).padStart(2, '0');
                            const minutes = String(now.getMinutes()).padStart(2, '0');
                            const seconds = String(now.getSeconds()).padStart(2, '0');

                            logForm.operateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

                            addOrderlog(logForm);
                          }




                        }).catch((error) => {
                          console.error("出库记录添加失败:", error);
                        });
                        this.updateInfoStatus(outBoundForm,this.form.storeTime);
                        // this.$modal.msgError("LOG2");
                        this.open = false;
                        this.getList();
                      });
                      return


                    }else{//头 进来 尾不确定
                      //多log！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
                      // this.form.storeStatus = 1;
                      // updateStore(this.form).then(response => {
                      //   this.$modal.msgSuccess("包裹入库成功1");
                      //   this.updateInfoStatus(this.form);
                      //   this.open = false;
                      //   this.getList();
                      // });




                        // this.open = false;
                        // this.getList();

                    }
                  }

                }
                else if(item.storeStatus === 1){//部分入库

                  if (item.stockTrackingnumber !== this.form.stockTrackingnumber){

                    if (item.packageStatus === 1){//包裹已经入过仓
                      whNum = whNum +1;//统计入过仓的包裹
                    }
                  }
                }
              }
            });
            if( sum === (whNum +1)){
              this.allStoreList.forEach((item, index) => {
                console.log(`第${index}个元素:`, item);
                if (item.orderNumber === this.form.orderNumber) {
                  if (item.stockTrackingnumber !== this.form.stockTrackingnumber){
                  const Dataform = {
                    id: item.id,
                    warehousing: item.warehousing,
                    orderNumber: item.orderNumber,
                    stockTrackingnumber: item.stockTrackingnumber,
                    commName: item.commName,
                    storeStatus: 0,
                    storeTime: item.storeTime,
                    packageStatus: item.packageStatus,
                    loginAccount: item.loginAccount,
                    orderCreateTime: item.orderCreateTime,
                    userAccount: item.userAccount,
                    userName: item.userName,
                    positionType: item.positionType,
                    positionNumber: item.positionNumber
                  };
                  updateStore(Dataform);
                  this.updateInfoStatus(Dataform,item.storeTime);
                    // this.$modal.msgError("LOG3");


                  }else {
                    if(this.form.positionType !== 0){

                      this.form.storeStatus = 0;

                      updateStore(this.form).then(response => {


                        // this.$modal.msgSuccess("入自己包裹入库成功");

                        //更新出库表
                        const outBoundForm = {
                          // id: item.id,
                          outboundId: "Out" + this.form.warehousing,
                          warehousing: this.form.warehousing,
                          orderNumber: this.form.orderNumber,
                          userName: this.form.userName,
                          outboundStatus: 1,
                          loginAccount: null
                        };

                        // 或使用 .then() 处理完成逻辑
                        addOutbound(outBoundForm).then(() => {
                          console.log("出库记录添加成功");

                        }).catch((error) => {
                          console.error("出库记录添加失败:", error);
                        });
                        this.updateInfoStatus(outBoundForm,this.form.storeTime);
                        // this.$modal.msgError("LOG4");



                        let isActive = true; // 初始值为 false，后续可以修改


                        this.logList.forEach((item, index) => {
                          if(item.stockTrackingnumber === this.form.stockTrackingnumber){
                            isActive = false;
                          }
                        });
                        //log
                        if(isActive){
                          const logForm = {
                            id: null,
                            orderNumber: this.form.orderNumber,
                            operateType: 11,
                            operateTime: null,
                            userAccount: this.$store.state.user.name,
                            userName: this.form.userName,
                            commName: this.form.commName,
                            stockTrackingnumber: this.form.stockTrackingnumber
                          };

                          // 生成符合数据库 datetime 格式的时间字符串（本地时区，格式如 "2024-03-29 15:30:45"）
                          const now = new Date();
                          const year = now.getFullYear();
                          const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零（3 → "03"）
                          const day = String(now.getDate()).padStart(2, '0');
                          const hours = String(now.getHours()).padStart(2, '0');
                          const minutes = String(now.getMinutes()).padStart(2, '0');
                          const seconds = String(now.getSeconds()).padStart(2, '0');

                          logForm.operateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

                          addOrderlog(logForm);
                        }


                        this.open = false;
                        this.getList();
                      });
                    }
                  }
                }
              });
            }
            else{
              this.form.storeStatus = 1;
              updateStore(this.form).then(response => {
                this.$modal.msgSuccess("包裹入库成功");
                this.updateInfoStatus(this.form,this.form.storeTime);
                // this.$modal.msgError("LOG5");



                let isActive = true; // 初始值为 false，后续可以修改


                this.logList.forEach((item, index) => {
                  if(item.stockTrackingnumber === this.form.stockTrackingnumber){
                    isActive = false;
                  }
                });
                //log
                if(isActive){
                  const logForm = {
                    id: null,
                    orderNumber: this.form.orderNumber,
                    operateType: 11,
                    operateTime: null,
                    userAccount: this.$store.state.user.name,
                    userName: this.form.userName,
                    commName: this.form.commName,
                    stockTrackingnumber: this.form.stockTrackingnumber
                  };

                  // 生成符合数据库 datetime 格式的时间字符串（本地时区，格式如 "2024-03-29 15:30:45"）
                  const now = new Date();
                  const year = now.getFullYear();
                  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零（3 → "03"）
                  const day = String(now.getDate()).padStart(2, '0');
                  const hours = String(now.getHours()).padStart(2, '0');
                  const minutes = String(now.getMinutes()).padStart(2, '0');
                  const seconds = String(now.getSeconds()).padStart(2, '0');

                  logForm.operateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

                  addOrderlog(logForm);
                }


                this.open = false;
                this.getList();
              });
            }
          } else {
            this.$modal.msgWarning("请填写入库时间或选择仓位");
            this.open = false;
            this.getList();
          }
        }
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStore(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStore(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除入库管理编号为"' + ids + '"的数据项？').then(function() {
        return delStore(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/store/export', {
        ...this.queryParams
      }, `store_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
